import { showToast } from '../utils/util'

// 默认API配置
const config = {
  baseUrl: 'http://localhost:3000' // 默认后端地址
}

// 尝试从manifest.json或全局变量获取配置
try {
  const appConfig = __wxConfig || uni.getApp().globalData.config
  if (appConfig && appConfig.baseUrl) {
    config.baseUrl = appConfig.baseUrl
  }
} catch (e) {
  console.warn('无法获取应用配置，使用默认API地址')
}

const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    const header = {}
    
    if (token) {
      header['Authorization'] = `Bearer ${token}`
    }

    uni.request({
      url: `${config.baseUrl}${options.url}`,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        ...header,
        ...(options.header || {})
      },
      success: (res) => {
        if (res.statusCode !== 200 || res.data.code !== 200) {
          showToast(res.data.message || '请求失败')
          reject(res.data)
        } else {
          resolve(res.data)
        }
      },
      fail: (err) => {
        showToast(err.errMsg || '请求失败')
        reject(err)
      }
    })
  })
}

export default request